#include "test.h"

#include "i2cDriveM.h"

#define SHT_ADDR 	0xCA			//

mI2CTypedef_t ScI2c;				//io模拟i2c接口


//硬件接口
//SDA PD6
//SCL PD7

static void i2c_IoInit(void){
	//io初始化输出高，外部电路无上拉，内部需要上拉
	GPIO_InitTypeDef GPIO_Initure;

	GPIO_Initure.Pin = GPIO_PIN_6| GPIO_PIN_7;
	GPIO_Initure.OutputEn = DISABLE;
	GPIO_Initure.InputEn = ENABLE;
	GPIO_Initure.PullupEn = ENABLE;
	HAL_GPIO_Init(GPIOD, &GPIO_Initure);
}

static void i2c_Delay(void){
	delay_us(100);
}

static void i2c_SdaH(void){
	HAL_GPIO_SetInOut(GPIOD, GPIO_PIN_6, ENABLE, DISABLE);
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_6, GPIO_PIN_RESET);
}

static void i2c_SdaL(void){
	HAL_GPIO_SetInOut(GPIOD, GPIO_PIN_6, ENABLE, ENABLE);
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_6, GPIO_PIN_RESET);
}

static void i2c_SclH(void){
	HAL_GPIO_SetInOut(GPIOD,GPIO_PIN_7, ENABLE, DISABLE);
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_7, GPIO_PIN_RESET);
}

static void i2c_SclL(void){
	HAL_GPIO_SetInOut(GPIOD, GPIO_PIN_7, ENABLE, ENABLE);
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_7, GPIO_PIN_RESET);
}

static u8 i2c_ReadSda(void){
	return HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_6);
}

static u8 i2c_ReadScl(void){
	return HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_7);
}

//iic设备注册
void sc_i2c_init(mI2CTypedef_t *i2c)
{
	i2c->IIC_IO_INIT=i2c_IoInit;
	i2c->IIC_DELAY=i2c_Delay;
	i2c->IIC_SDA_H=i2c_SdaH;
	i2c->IIC_SDA_L=i2c_SdaL;
	i2c->IIC_SCL_H=i2c_SclH;
	i2c->IIC_SCL_L=i2c_SclL;
	i2c->IIC_READ_SDA=i2c_ReadSda;
	i2c->IIC_READ_SCL=i2c_ReadScl;
}

//从uWriteAddress地址开始写入len字节数据					//通常情况下可以这样读写，但是顶不住有些设备与众不同，所以具体读写时序还要看芯片手册
void sc_i2c_write(u8 uWriteAddress,u8 *buf,u8 len)
{
	i2c_Start(&ScI2c);
	i2c_SendByte(&ScI2c,SHT_ADDR|I2C_WR);
	i2c_WaitAck(&ScI2c);
	i2c_SendByte(&ScI2c,(uWriteAddress) & 0xFF);
	i2c_WaitAck(&ScI2c);
	while(len--){
		i2c_SendByte(&ScI2c,*buf++);
		i2c_WaitAck(&ScI2c);
	}
	i2c_Stop(&ScI2c);
}
//从uWriteAddress地址开始读出len字节数据
u8 sc_i2c_read(u8 uReadAddress,u8 *buf,u8 len)
{
	i2c_Start(&ScI2c);
	i2c_SendByte(&ScI2c,SHT_ADDR|I2C_WR);
	if(1==i2c_WaitAck(&ScI2c)){	//ERROR
		goto ERR;
	}
	i2c_SendByte(&ScI2c,uReadAddress);
	if(1==i2c_WaitAck(&ScI2c)){	//ERROR
		goto ERR;
	}
 //   i2c_Stop(&ScI2c);
	i2c_Start(&ScI2c);
	i2c_SendByte(&ScI2c,SHT_ADDR|I2C_RD);
	if(1==i2c_WaitAck(&ScI2c)){	//ERROR
		goto ERR;
	}
	while(len-->1){
		*buf++ = i2c_ReadByte(&ScI2c);
		i2c_Ack(&ScI2c);
	}
	*buf++ = i2c_ReadByte(&ScI2c);
	i2c_NAck(&ScI2c);
	i2c_Stop(&ScI2c);
	return 1;//正常返回
ERR:
	i2c_SdaErrorClear(&ScI2c);
	return 0;	
}

u8 sc_i2c_read_no_addr(u8 *buf,u8 len)
{
	i2c_Start(&ScI2c);
	i2c_SendByte(&ScI2c,SHT_ADDR|I2C_RD);
	if(1==i2c_WaitAck(&ScI2c)){	//ERROR
		goto ERR;
	}
	while(len-->1){
		*buf++ = i2c_ReadByte(&ScI2c);
		i2c_Ack(&ScI2c);
	}
	*buf++ = i2c_ReadByte(&ScI2c);
	i2c_NAck(&ScI2c);
	i2c_Stop(&ScI2c);
	return 1;//正常返回
ERR:
	i2c_SdaErrorClear(&ScI2c);
	return 0;	
}

//初始化
void sc_init(void)
{
    i2c_IoInit();
	sc_i2c_init(&ScI2c);
}

